package com.icart.controller.personController;


import com.icart.context.HttpUserContext;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.repositories.CouponRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.List;


@Controller
@RequestMapping("/person")
public class CouponController {

    @Autowired
    CouponRepository couponRepository;
    @Autowired
    HttpServletRequest request;

    /*优惠券*/
    @RequestMapping("/coupon")
    public String coupon(Model model) {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowtime=sdf.format(date);
        /*可使用优惠券*/
        List canuse=couponRepository.createNativeQuery("select cpid,feecaltype,feeval,ordamount,DATE_FORMAT(startdate,'%Y-%m-%d')startdate," +
                "DATE_FORMAT(enddate,'%Y-%m-%d')enddate,remark,(select n.chnname from bi_chn n where n.chnid=usechn)chnname,cpname " +
                " from cu_coupon where startdate<='"+nowtime+"'"+" and enddate>='"+nowtime+"' and stat=0");
        model.addAttribute("canuse",canuse);

          /*已使用优惠券*/
        List hasuse=couponRepository.createNativeQuery("select feecaltype,feeval,ordamount,DATE_FORMAT(startdate,'%Y-%m-%d')startdate," +
                "DATE_FORMAT(enddate,'%Y-%m-%d')enddate,remark,(select n.chnname from bi_chn n where n.chnid=usechn)chnname,cpname " +
                " from cu_coupon where stat=1");
        model.addAttribute("hasuse",hasuse);

         /*已过期优惠券*/
        List outuse=couponRepository.createNativeQuery("select feecaltype,feeval,ordamount,DATE_FORMAT(startdate,'%Y-%m-%d')startdate," +
                "DATE_FORMAT(enddate,'%Y-%m-%d')enddate,remark,(select n.chnname from bi_chn n where n.chnid=usechn)chnname,cpname " +
                " from cu_coupon where enddate<'"+nowtime+"' and stat=0");
        model.addAttribute("outuse",outuse);
        return "person/coupon/coupon";
    }

    /*优惠券*/
    @RequestMapping("/use")
    public String use(@RequestParam(required = false,name = "cpid")Long cpid, Model model) {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=null;
        flag=couponRepository.update(cpid);
        if(flag==1){
            return "redirect:/person/coupon";
        }else {
            return "redirect:/person/coupon";
        }

    }

}